package com.party.mobile.web.controller.crowdfundMultiple;

import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.EventGradation;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.ProjectGradation;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.core.service.crowdfund.IProjectGradationService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: huangzequn
 * @Date: 2019/3/19 17:26
 * 众筹多场活动
 */
@Controller
@RequestMapping(value = "crowdfund/activity/multiple")
public class CrowdfundActivityMultipleController {

    protected static Logger logger = LoggerFactory.getLogger(CrowdfundActivityMultipleController.class);

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IProjectGradationService projectGradationService;

    @Autowired
    private IEventGradationService eventGradationService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IProjectService projectService;

    /***
     * 根据后台设置查询所有的报名者  同行戈友
     * @param targetId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "projectList")
    public AjaxResult projectList(String targetId, Page page) {
        try {
            if (StringUtils.isEmpty(targetId)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
            }
            Activity activity = activityService.get(targetId);
            if (2 == activity.getPersonalPopularPageState()) {
                //2代表不显示报名人员
                return AjaxResult.success("不显示报名人员");
            }
            CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(targetId);
            if (crowdfundEvent == null) {
                return AjaxResult.error(PartyCode.DATA_UNEXIST, "项目不存在");
            }

            if (1 == activity.getPersonalPopularPageState()) {
                //1代表显示该项目报名人员
                List<Project> projectList = projectGradationService.getProjectByActivityId(targetId, page);
                return AjaxResult.success(getProjectList(projectList, crowdfundEvent), page);
            }

            if (0 == activity.getPersonalPopularPageState()) {
                //0代表显示所属主题报名人员
                List<Project> projectList = projectGradationService.queryProjectByTargetId(activity.getEventId(), page);
                return AjaxResult.success(getProjectList(projectList, crowdfundEvent), page);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("同行戈友人员列表异常：targetId-{}", targetId, e);
            return AjaxResult.error();
        }
    }


    /**
     * 同行戈友代码封装
     *
     * @param projectList
     * @param crowdfundEvent
     * @return
     */
    public List<Project> getProjectList(List<Project> projectList, CrowdfundEvent crowdfundEvent) {


        if (projectList.size() < 1) {
            return projectList;
        }

        Map<String, Object> params = new HashMap<>();
        /**
         * 找出当前阶段的目标金额
         */
        EventGradation eventGradation = eventGradationService.findOngoingGradation(crowdfundEvent.getId());
        if(null==eventGradation){
            //最后阶段主题
            eventGradation = eventGradationService.getTheLastGradation(crowdfundEvent.getId());
        }

        /**
         * 找出所有报名者已消费的总金额，比如说当前系统时间是第三阶段，则需要找出第一第二阶段的目标金额
         * 并且加条件过滤出来   第一第二阶段标记已参赛的  或者 有阶段筹满时间的
         */
        params.put("eventId", crowdfundEvent.getId());
        List<ProjectGradation> projectGradationList = projectGradationService.getProjectGradationByTargetId(params);
        projectGradationList.removeAll(Collections.singleton(null));
        for (Project project : projectList) {
            Double div = BigDecimalUtils.div(project.getActualAmount(), eventGradation.getPrice().floatValue(), 2);
            project.setPercentage(div.floatValue());
            for (ProjectGradation projectGradation : projectGradationList) {
                if (project.getId().equals(projectGradation.getProjectId())) {
                    float sub = BigDecimalUtils.sub(project.getActualAmount(), projectGradation.getSumTargetAmount().floatValue());
                    div = BigDecimalUtils.div(sub, eventGradation.getPrice().floatValue(), 2);
                    project.setPercentage(div.floatValue());
                }
            }
        }
        /** 排序  当前阶段众筹成功的排在前面，先报名的排在前面*/
        Collections.sort(projectList, new Comparator<Project>() {
            @Override
            public int compare(Project o1, Project o2) {
                int i = o2.getPercentage().compareTo(o1.getPercentage());
                if (i == 0) {
                    return o1.getCreateDate().compareTo(o2.getCreateDate());
                }
                return i;
            }
        });
        return projectList;
    }


    /***
     * 个人排行榜  H5个人众筹页改版 2018-12-20   分页
     * @type type 0代表速度榜，1代表人气榜，2代表财富榜
     * @activityId targetId  项目id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "personalList")
    public AjaxResult personalList(String type, Page page, String targetId) {
        try {
            if (StringUtils.isEmpty(targetId) || targetId.equals("undefined")) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
            }
            if (StringUtils.isEmpty(type)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "排行榜类型不能为空");
            }
            CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(targetId);
            if (crowdfundEvent == null) {
                return AjaxResult.error(PartyCode.DATA_UNEXIST, "项目不存在");
            }
            Map<String, String> params = new HashMap<>();
            params.put("type", type);
            params.put("targetId", targetId);
            if (1 == crowdfundEvent.getPersonalRanking()) {
                //说明是自定义显示的人数
                final int limit = page.getLimit();
                if (crowdfundEvent.getPeopleNum() < page.getLimit() * page.getPage()) {
                    page.setLimit(crowdfundEvent.getPeopleNum() - (page.getLimit() * page.getPage() - page.getLimit()));
                    if (page.getLimit() == 0) {
                        return AjaxResult.success("没有数据啦");
                    }
                    List<ProjectGradation> projectList = getToProjectGradationList(page, type, params, crowdfundEvent);
                    page.setLimit(limit);
                    if (page.getPage() > 1) {
                        projectList = getToProjectList(page, projectList);
                    }
                    return AjaxResult.success(projectList, page);
                } else {
                    List<ProjectGradation> projectList = getToProjectGradationList(page, type, params, crowdfundEvent);
                    if (page.getPage() > 1) {
                        projectList = getToProjectList(page, projectList);
                    }
                    return AjaxResult.success(projectList, page);
                }
            } else if (0 == crowdfundEvent.getPersonalRanking()) {
                List<ProjectGradation> projectList = getToProjectGradationList(page, type, params, crowdfundEvent);
                if (page.getPage() > 1) {
                    projectList = getToProjectList(page, projectList);
                }
                return AjaxResult.success(projectList, page);
            } else {
                return AjaxResult.success("不显示排行榜");
            }
        } catch (Exception e) {
            logger.error("个人排行榜分页异常：type-{}，targetId-{}", type, targetId, e);
            return AjaxResult.error();
        }
    }


    /***
     * 个人排行榜     个人信息
     * @type type 0代表速度榜，1代表人气榜，2代表财富榜
     * @targetId targetId  项目id
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "personal")
    public AjaxResult personal(String targetId, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        try {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(targetId);
            if (crowdfundEvent == null) {
                return AjaxResult.success("个人排行榜个人信息   有问题");
            }
            if (2 == crowdfundEvent.getPersonalRanking()) {
                return AjaxResult.success("不显示个人排行榜个人信息");
            }
            Map<String, Object> projectMap = new HashMap<>();
            Map<String, String> params = new HashMap<>();
            EventGradation eventGradation = eventGradationService.findOngoingGradation(crowdfundEvent.getId());
            if(null==eventGradation){
                //最后阶段主题
                eventGradation = eventGradationService.getTheLastGradation(crowdfundEvent.getId());
            }
            params.put("projectGradationId", eventGradation.getId());
            params.put("targetId", targetId);
            params.put("memberId", currentUser.getId());
            //速度
            ProjectGradation speedProject = projectGradationService.popularity(params, "0");
            //人气
            ProjectGradation popularityProject = projectGradationService.popularity(params, "1");
            //财富
            ProjectGradation wealthProject = projectGradationService.popularity(params, "2");
            if (null == speedProject) {
                Project byMemberId = projectService.getByMemberId(targetId, currentUser.getId());
                if (byMemberId != null) {
                    speedProject = new ProjectGradation();
                    speedProject.setLogo(byMemberId.getLogo());
                    speedProject.setProjectId(byMemberId.getId());
                    speedProject.setRealname(byMemberId.getRealname());
                }
            }

            projectMap.put("speedProject", speedProject);
            projectMap.put("popularityProject", popularityProject);
            projectMap.put("wealthProject", wealthProject);
            return AjaxResult.success(projectMap);
        } catch (Exception e) {
            logger.error("个人排行榜个人信息异常--targetId：{}，memberId：{}", targetId, currentUser.getId(), e);
            return AjaxResult.error();
        }
    }


    /***
     * 个人排行榜  H5个人众筹页改版 2018-12-20   分页
     * @param page
     * @param list
     * @return
     */
    public List<ProjectGradation> getToProjectList(Page page, List<ProjectGradation> list) {
        for (ProjectGradation ProjectGradation : list) {
            Integer ranking = ProjectGradation.getRanking();
            int current = page.getPage();
            int size = page.getLimit();
            ProjectGradation.setRanking((current - 1) * size + ranking);

        }
        return list;
    }


    /***
     * 个人排行榜封装查询
     * @param page
     * @param type
     * @param params
     * @param crowdfundEvent
     * @return
     */
    public List<ProjectGradation> getToProjectGradationList(Page page, String type, Map<String, String> params,
                                                            CrowdfundEvent crowdfundEvent) {
        List<ProjectGradation> projectList;
        if ("0".equals(type)) {
            //多场活动速度榜
            EventGradation eventGradation = eventGradationService.findOngoingGradation(crowdfundEvent.getId());
            if(null==eventGradation){
                //最后阶段主题
                eventGradation = eventGradationService.getTheLastGradation(crowdfundEvent.getId());
            }
            params.put("projectGradationId", eventGradation.getId());
            projectList = projectGradationService.speedList(params, page);
        } else {
            projectList = projectGradationService.speedList(params, page);
        }
        return projectList;
    }
}
